<?php

# shield PHP warning and error prompt
# ini_set("display_errors", "Off");

function output($obj) {
  echo json_encode($obj, JSON_UNESCAPED_UNICODE);
}

function inpput($key, $def = null) {
  $input_content = file_get_contents('php://input');
  $post_arr      = json_decode($input_content, true);
  if (is_array($post_arr)) {
    if (isset($post_arr[$key])) {
      return $post_arr[$key];
    }
  }
  if (isset($_GET[$key])) {
    return $_GET[$key];
  }
  return $def;
}

function is_json($string) {
  json_decode($string);
  return (json_last_error() == JSON_ERROR_NONE);
}

function json_stringify($obj) {
  $str = json_encode($obj, JSON_UNESCAPED_UNICODE);
  // exception err in json_encode
  if (gettype($str) === 'string') {
    return $str;
  } else {
    return '{}';
  }
}

function json_parse($json = '', $assoc = true) {
  if (! $json) {
    return null;
  }
  try {
    $object = json_decode($json, $assoc);
    $error  = json_last_error();
    if ($error == JSON_ERROR_NONE) {
      return $object;
    } else {
      return $json;
    }
  } catch (\Exception $e) {
    return $json;
  }
}

function query_parse($data = [], $assoc = true) {
  $data_new = [];
  foreach ($data as $row => $line) {
    foreach ($line as $col => $cell) {
      $data_new[$row][$col] = json_parse($cell, $assoc);
    }
  }
  return $data_new;
}

function timestamp() {
  $mill_time  = microtime();
  $timeInfo   = explode(' ', $mill_time);
  $milis_time = sprintf('%d%03d', $timeInfo[1], $timeInfo[0] * 1000);
  return (int)$milis_time;
}

function verify_ttl($tx, $rx, $min_ttl, $max_ttl) {
  $status    = 1;
  $info      = 'Requested refresh.';
  $timestamp = timestamp();
  if ($timestamp - $rx < $min_ttl) {
    $info   = 'Ignored refresh, ' . ($timestamp - $rx) . ' < ' . $min_ttl . '.';
    $status = 0;
  }
  if ($rx < $tx) {
    $info   = 'Ignored refresh, waiting for response.';
    $status = 0;
  }
  if ($timestamp - $tx > $max_ttl) {
    $info   = 'Requested refresh, ttl exceeded ' . $max_ttl . '.';
    $status = 1;
  }
  return [
    'status' => $status,
    'info'   => $info,
    'time'   => $timestamp,
  ];
}

function get_client_ip() {
  if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) {
    $ip = getenv("HTTP_CLIENT_IP");
  } elseif (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) {
    $ip = getenv("HTTP_X_FORWARDED_FOR");
  } elseif (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) {
    $ip = getenv("REMOTE_ADDR");
  } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) {
    $ip = $_SERVER['REMOTE_ADDR'];
  } else {
    $ip = "unknown";
  }
  return $ip;
}

function get_client_seat($ip = null) {
  $ip ?? $ip   = get_client_ip();
  $client_list = json_decode(file_get_contents('./seatIP.json'), true);

  // add test seat
  $client_list[] = ['seat' => ['TM12'], 'ip' => ['127.0.0.1', '10.202.91.101']];

  foreach ($client_list as $client) {
    if ($client['ip'][0] == $ip || $client['ip'][1] == $ip) {
      return $client['seat'][0];
    }
  }
  return '未知设备';
}

function truncate_chars($str, $len = 768, $dotted = true) {
  $maxLength = $dotted ? $len - 3 : $len;

  if (mb_strlen($str) > $maxLength) {
    $str = mb_substr($str, 0, $maxLength) . $dotted ? '...' : '';
  }

  return $str;
}

function forbidden_acc() {
  $ip       = get_client_ip();
  $approved = true;
  // if (stripos($ip, '10.202') !== false) {
  //   // 允许终端sipds
  //   $approved = true;
  // }
  // if (stripos($ip, '127.0') !== false) {
  //   // 允许本地调试
  //   $approved = true;
  // }
  // if (stripos($ip, '192.168') !== false) {
  //   // 禁止区管sipds
  //   $approved = false;
  // }
  // if (stripos($ip, '10.99') !== false) {
  //   // 禁止区管sipds
  //   $approved = false;
  // }
  if (! $approved) {
    die();
  }
}

function keepOnlyChinese($str) {
  return preg_replace('/[^\x{4e00}-\x{9fa5}]/u', '', $str);
}{

}
